#pragma once

static HBITMAP LoadImgFromRes(Gdiplus::Bitmap** ppImage, UINT pResourceID, HMODULE hInstance, LPCTSTR pResourceType)
{
	HBITMAP hBitmap = NULL;
	LPCTSTR pResourceName = MAKEINTRESOURCE(pResourceID);

	HRSRC hResource = FindResource(hInstance, pResourceName, pResourceType);
	if(!hResource)
	{
		TRACE(_T("FindResource Failed\n"));
		return NULL;
	}

	DWORD dwResourceSize = SizeofResource(hInstance, hResource);
	if(!dwResourceSize)
	{
		TRACE(_T("SizeofResource Failed\n"));
		return NULL;
	}

	const void* pResourceData = LockResource(LoadResource(hInstance, hResource));
	if(!pResourceData)
	{
		TRACE(_T("LockResource Failed\n"));
		return NULL;
	}

	HGLOBAL hResourceBuffer = GlobalAlloc(GMEM_MOVEABLE, dwResourceSize);
	if(!hResourceBuffer)
	{
		TRACE(_T("GlobalAlloc Failed\n"));
		GlobalFree(hResourceBuffer);
		return NULL;
	}

	void* pResourceBuffer = GlobalLock(hResourceBuffer);
	if(!pResourceBuffer)
	{
		TRACE(_T("GlobalLock Failed\n"));
		GlobalUnlock(hResourceBuffer);
		GlobalFree(hResourceBuffer);
		return NULL;
	}

	CopyMemory(pResourceBuffer, pResourceData, dwResourceSize);
	IStream* pIStream = NULL;

	if(CreateStreamOnHGlobal(hResourceBuffer, FALSE, &pIStream)==S_OK)
	{
		if(ppImage != NULL)
		{
			*ppImage = Gdiplus::Bitmap::FromStream(pIStream);
			pIStream->Release();

			GlobalUnlock(hResourceBuffer);
			GlobalFree(hResourceBuffer);

			return NULL;
		}
		else
		{
			Gdiplus::Bitmap *pBitmap = Gdiplus::Bitmap::FromStream(pIStream);
			pIStream->Release();

			GlobalUnlock(hResourceBuffer);
			GlobalFree(hResourceBuffer);

			if(pBitmap == NULL)
			{
				return NULL;
			}

			Gdiplus::Status result = pBitmap->GetLastStatus();
			if(result == Gdiplus::Ok)
			{
				pBitmap->GetHBITMAP(NULL, &hBitmap);
				delete pBitmap;
				return hBitmap;
			}

			delete pBitmap;
		}
	}

	GlobalUnlock(hResourceBuffer);
	GlobalFree(hResourceBuffer);

	return NULL;
}